﻿using MongoDB.Driver;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.DataLayer.Shared;
using System;

namespace Sustainalytics.DataLayer.CompanyHistory
{
    public class CompanyPerformanceHistoryRepository : RepositoryCollection<CompanyHistoricalPerformance>
    {
        private readonly string _databaseName;
        private readonly string _name;

        public CompanyPerformanceHistoryRepository(string mongoDbUrl, string collectionName = null) : base(mongoDbUrl, collectionName)
        {
            _databaseName = new MongoUrl(mongoDbUrl).DatabaseName;
            _name = collectionName;
        }

        public override bool Create(CompanyHistoricalPerformance entity)
        {
            return CreateOrUpdate(entity);
        }

        public override bool CreateOrUpdate(CompanyHistoricalPerformance entity)
        {
            try
            {
                var query = Builders<CompanyHistoricalPerformance>.Filter.Eq(x=> x.Id, entity.Id);
                var update = Builders<CompanyHistoricalPerformance>.Update.PushEach(
                    x => x.Last36Months,
                    entity.Last36Months, 36, 0, Builders<CompanyHistoryData>.Sort.Descending(x => x.Date));

                var updateResult =  Collection().UpdateOne(query, update, new UpdateOptions() { IsUpsert = true });

                return updateResult.IsAcknowledged;
            }
            catch (Exception ex)
            {
                RepositoryLog.Log("Save", entity, ex, _databaseName, _name);
                throw;
            }
        }
    }
}
